import javax.xml.soap.Node;

// 二叉树先序序列化和反序列化 (先序遍历实现)
// 测试链接 : https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
public class PreorderSerializeAndDeserialize {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int v) {
            val = v;
        }
    }

    public class Codec {

        //序列化
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            func(sb, root);
            return sb.toString();
        }
        public void func(StringBuilder sb,TreeNode root) {
            if(root != null) {
                sb.append(root.val + ",");
                func(sb,root.left);
                func(sb,root.right);
            }else{
                sb.append("#,");
            }
        }

        public int cnt;  //表示消耗元素的下标
        //反序列化
        public TreeNode deserialize(String data) {
            String[] arr = data.split(",");
            cnt = 0;
            return create(arr);
        }

        public TreeNode create(String[] arr) {
            String str = arr[cnt++];
            TreeNode node = null;
            if(!str .equals("#") ){
                node = new TreeNode(Integer.valueOf(str));
                node.left = create(arr);
                node.right = create(arr);
            }
            return node;
        }
    }
}
